<?php

namespace backend\controllers;

use backend\utils\AppUtil;
use backend\utils\requestData;
use common\models\User;
use common\models\UsersBound;
use Yii;
use yii\helpers\Url;

class LoginController extends BaseController
{
    public $defaultAction = 'oauth-login';
    public $enableCsrfValidation = false;

    /**
     * @desc cas 登录
     * @return \yii\web\Response
     * @Date: 2024/11/6
     */
    public function actionCasLogin()
    {
        if (Yii::$app->user->isGuest) {
            require_once Url::to('@common') . '/extensions/cas/phpCAS.php';
            //指定log文件
            \phpCAS::setDebug('files/caslog.log');
            //指定cas地址，最后一个true表示是否cas服务器为https，第二个参数为域名或是ip，第三个参数为服务器端口号，第四个参数为上下文路径
            \phpCAS::client(CAS_VERSION_2_0, 'basic.jxeduyun.com', 443, 'sso', true);
            // no SSL validation for the CAS server
            \phpCAS::setNoCasServerValidation();
            \phpCAS::handleLogoutRequests();
            // force CAS authentication
            try {
                $auth = \phpCAS::forceAuthentication();
            } catch (\Exception $exc) {
                return $this->redirect(['other/cas-login']);
            }
            $loginUserName = \phpCAS::getUser();
            $user = User::findOne(['username' => $loginUserName]);
            //判断用户是否存在，不存在写入
            if (!$user) {
                throw new \yii\web\BadRequestHttpException('系统中不存在该用户.');
            }
            //登录处理
            Yii::$app->user->login($user);
        }
        $users = User::findIdentity(Yii::$app->user->id);
        $user_type = intval($users->user_type);
        if ($user_type) {
            return $this->redirect(['site/home']);
        } else {
            return $this->redirect(['other/cas-logout']);
        }
    }

    /**
     * @desc cas 退出
     * @return void
     * @Date: 2024/11/6
     */
    public function actionCasLogout()
    {
        //引入文件
        require_once Url::to('@common') . '/extensions/cas_source/CAS.php';
        //指定log文件
        \phpCAS::setDebug('files/caslog.log');
        //指定cas地址，第二个参数为域名或是ip，第三个参数为服务器端口号，第四个参数为上下文路径，第5个参数true表示是否cas服务器为https
        \phpCAS::client(CAS_VERSION_2_0, 'basic.jxeduyun.com', 443, 'sso', true);

        // no SSL validation for the CAS server
        \phpCAS::setNoCasServerValidation();
        \phpCAS::handleLogoutRequests();
        // force CAS authentication
        \phpCAS::forceAuthentication();
        // logout if desired
        $param = ["service" => Yii::$app->request->hostInfo . '/other/cas-login'];//退出登录后返回
        \phpCAS::logout($param);
    }


    /**
     * @desc
     * @return \yii\web\Response
     * @Date: 2024/11/6
     */
    public function actionOauthLogin()
    {
        // 两次请求的返回demo
        // $aa = '{"code":"1","message":"success","data":"31e9be88622be49e56f9cf7acd2d7c0251e4df7d94b056328634bb6f83e6dac127c270ff57ba216d9de5be3d27e72e6a40369603ab409bba","success":true}';
        // $aa = '{"code":"1","message":"success","data":{"userId":"31e9be88622be49e56f9cf7acd2d7c0251e4df7d94b056328634bb6f83e6dac127c270ff57ba216d9de5be3d27e72e6a40369603ab409bba","openId":"31e9be88622be49e56f9cf7acd2d7c0251e4df7d94b056328634bb6f83e6dac127c270ff57ba216d9de5be3d27e72e6a40369603ab409bba","userName":"三方测勿动","loginName":null,"userPhoto":"https://download.cycore.cn/edc/openapi/avatar_default_teacher_200_m_2.png?default","schoolId":"f95ba93aee210bc1ed773b64178a1c061f2be8b971190bc5eb65a0ee6f6460b0f805d4527a5b337fa6a2e82fb08d15659e2d7bbb9fe0e8d1","orgType":1,"schoolName":"智慧教育测试学校","userRoleList":null,"province":"1366","city":"1475","district":"1487"},"success":true}';

        if (Yii::$app->user->isGuest) {
            $accessToken = Yii::$app->request->get('accessToken');
            $state = Yii::$app->request->get('state');
            $expires_in = Yii::$app->request->get('expires_in');
            $url = requestData::URL . '/authorize?appkey=' . requestData::APPKEY . '&redirectUri=' . Yii::$app->request->hostInfo . '/login/oauth-login&state=1';
            if ($accessToken) {
                $openid_json_data = requestData::sendCurl('/getOpenId', 60, [
                    'appkey' => requestData::APPKEY,
                    'appsecret' => requestData::APPSECRET,
                    'accessToken' => $accessToken,
                ]);

                $openid_data = json_decode($openid_json_data);
                $code_code = $openid_data->code;
                $openId = $openid_data->data;
                if ($code_code == '-1') {
                    // 验证失败
                    return $this->redirect($url);
                }
                $user_json_data = requestData::sendCurl('/getUserInfo', 60, [
                    'appkey' => requestData::APPKEY,
                    'accessToken' => $accessToken,
                    'openId' => $openId,
                ]);
                $user_data = json_decode($user_json_data);
                $code_code = $user_data->code;
                $user_data_data = $user_data->data;
                if ($code_code == '-1') {
                    // 验证失败
                    return $this->redirect($url);
                }
                $userId = $user_data_data->userId;
                $userName = $user_data_data->userName;
                $schoolName = $user_data_data->schoolName;

                $users_id = UsersBound::getUsersIdByThirdUserId($userId);
                if ($users_id === false) {
                    $cache_key = AppUtil::init_uuid();
                    Yii::$app->cache->set($cache_key, [
                        'third_user_id' => $userId,
                        'third_user_name' => $userName,
                        'third_school_name' => $schoolName,
                    ], 1800);// 缓存秒数
                    return $this->redirect(['login/bound', 'key' => $cache_key, 'userName' => $userName, 'accessToken' => $accessToken]);
                }
                $user = User::findOne($users_id);
                //判断用户是否存在，不存在写入
                if (!$user) {
                    throw new \yii\web\BadRequestHttpException('系统中不存在该用户.');
                }
                //登录处理
                Yii::$app->user->login($user);
            } else {
                // 未登录
                return $this->redirect($url);
            }
        }

        $users = User::findIdentity(Yii::$app->user->id);
        $user_type = intval($users->user_type);
        if ($user_type) {
            return $this->redirect(['site/home']);
        } else {
            return $this->redirect(['login/oauth-logout']);
        }
    }

    /**
     * @desc
     * @return \yii\web\Response
     * @Date: 2024/11/6
     */
    public function actionOauthLogout()
    {
        Yii::$app->user->logout();
        $url = requestData::URL . '/authorize?appkey=' . requestData::APPKEY . '&redirectUri=' . Yii::$app->request->hostInfo . '/login/oauth-login&state=1';
        return $this->redirect($url);
    }

    /**
     * @desc
     * @return string
     * @Date: 2024/11/6
     */
    public function actionBound()
    {
        $key = Yii::$app->request->get('key');
        $userName = Yii::$app->request->get('userName');
        $accessToken = Yii::$app->request->get('accessToken');
        return $this->renderPartial('bound', [
            'userName' => $userName,
            'key' => $key,
            'accessToken' => $accessToken,
        ]);
    }

    /**
     * @desc
     * @return false|string
     * @Date: 2024/11/6
     */
    public function actionAjaxBound()
    {
        $cache_key = Yii::$app->request->post('key'); // 缓存id
        $username = Yii::$app->request->post('username');
        $password = Yii::$app->request->post('password');
        $model = User::find()->where(['username' => $username, 'password' => md5($password), 'is_login' => 1])->one();
        $err_array = [];
        if (!$model) {
            $result['state'] = false;
            $result['code'] = '0';
            $result['msg'] = '您输入的账号或密码错误';
            $result['data'] = ['error_arr' => $err_array];
            return json_encode($result);
        }

        $data = Yii::$app->cache->get($cache_key);
        if ($data === false) {
            $result['state'] = false;
            $result['code'] = '0';
            $result['msg'] = '请求的信息已经超时 请重新获取!';
            $result['data'] = ['error_arr' => $err_array];
            return json_encode($result);
        }
        $third_user_id = $data['third_user_id'];
        $third_user_name = $data['third_user_name'];
        $third_school_name = $data['third_school_name'];
        $users_id = UsersBound::getUsersIdByThirdUserId($third_user_id);
        if ($users_id) {
            $result['state'] = false;
            $result['code'] = '0';
            $result['msg'] = '当前用户已经完成绑定 请勿多次绑定。';
            $result['data'] = ['error_arr' => $err_array];
            return json_encode($result);
        }
        $data['users_id'] = $model->uuid;
        list($res, $model) = UsersBound::edit($data, $model->uuid, '');
        if (!$res) {
            $err_array = AppUtil::get_error($model);
            $result['state'] = false;
            $result['code'] = '0';
            $result['msg'] = '绑定失败';
            $result['data'] = ['error_arr' => $err_array];
            return json_encode($result);
        }

        $result['state'] = true;
        $result['code'] = '200';
        $result['msg'] = '绑定成功';
        $result['data'] = ['error_arr' => []];
        return json_encode($result);
    }

}
